package com.wz.activity;

import java.util.ArrayList;
import java.util.List;

import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.wz.bean.Festival;
import com.wz.bean.FestivalData;
import com.wz.bean.Msg;
import com.wz.bean.SendedMsg;
import com.wz.receiver.DeliverBroadcastReceiver;
import com.wz.receiver.SendBroadcastReceiver;
import com.wz.shortmesg.SmsBiz;
import com.wz.util.ToastUtil;
import com.wz.view.flowlayout.FlowLayout;
import com.wz.view.flowlayout.TagAdapter;
import com.wz.view.flowlayout.TagFlowLayout;

public class SendMesgActivity extends AppCompatActivity{
	private FloatingActionButton mfabSend;
	private EditText meidtmesg;
	private Button mbtnAdd;
	private TagFlowLayout mFlContacts;
	private View mlayoutLoading;
	
	private int REQUESTCODE = 1;  //请求码
	
	private int mfestivalId;
	private int msgId;
	
	private Festival mfestival;
	private Msg msg;
	
	public static final String KEY_FESTIVAL_ID ="key_Festival_id";
	public static final String KEY_MSG_ID ="key_msg_id";
	
	//存放接受短信的联系人姓名
	public static volatile List<String> mcontactNames = new ArrayList<String>();
	//存放接受短信的联系人号码
	public static volatile List<String> mcontactNums = new ArrayList<String>();
	
	private LayoutInflater miInflater; //布局填充器
	
	
	public static final String ACTION_SEND_MSG = "ACTION_SEND_MSG";
	public static final String ACTION_DELIVER_MSG = "ACTION_DELIVER_MSG";
	private PendingIntent msendPI;
	private PendingIntent mdeliverPI;
	//广播
	private BroadcastReceiver msendBroadcastReceiver;
	private BroadcastReceiver mdeliverBroadcastReceiver;
	
	public static volatile int mtotalCount;
	public static volatile int mmesgSendCount = 0;
	
	private SmsBiz smsBiz = null;
	
	private TagAdapter<String> tagAdapter;
	
	@Override
	protected void onCreate(@Nullable Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.send_mesg_activity);
		
		miInflater = LayoutInflater.from(this);
		//一定要先初始化数据,用于获取参数
		initDatas();
		
		//然后初始化界面
		initView();
		
		initEvent();
	
		initReceivers();
		
		smsBiz = new SmsBiz(this);
	}
	
	
	private void initReceivers() {
		
		Intent sendIntent = new Intent(ACTION_SEND_MSG);
		msendPI = PendingIntent.getBroadcast(this, 0, sendIntent, 0);
		
		Intent deliverIntent = new Intent(ACTION_DELIVER_MSG);
		mdeliverPI = PendingIntent.getBroadcast(this, 0, deliverIntent, 0);
	
		//注册广播,一定要onDestroy 方法中取消广播,释放资源
		msendBroadcastReceiver = new SendBroadcastReceiver();
		mdeliverBroadcastReceiver = new DeliverBroadcastReceiver();
	    this.registerReceiver(msendBroadcastReceiver, new IntentFilter(ACTION_SEND_MSG));
	    this.registerReceiver(mdeliverBroadcastReceiver, new IntentFilter(ACTION_DELIVER_MSG));
	    
	    
	}


	private void initEvent() {
		mbtnAdd.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
				startActivityForResult(intent, REQUESTCODE);

			}
		});

		mfabSend.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (mcontactNums.size() == 0) {
					ToastUtil.showShort(SendMesgActivity.this, "请选择联系人");
					return;
				}

				String text = meidtmesg.getText().toString();
				if (TextUtils.isEmpty(text)) {
					ToastUtil.showShort(SendMesgActivity.this, "短信内容不能为空");
					return;
				}
				// 显示进度条
				mlayoutLoading.setVisibility(View.VISIBLE);

				// 返回短信发送数量
				mtotalCount = smsBiz.sendMsg(mcontactNums, bulidSendMsg(text), msendPI, mdeliverPI);

			}
		});

		// 创建适配器
		tagAdapter = new TagAdapter<String>(mcontactNames) {
			@Override
			public View getView(FlowLayout parent, int position, String s) {
				TextView tv = (TextView) miInflater.inflate(R.layout.tag, mFlContacts, false);
				tv.setText(s);
				return tv;
			}
		};
		// 设置适配器
		mFlContacts.setAdapter(tagAdapter);

		//设置流布局的点击事件
		mFlContacts.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
			@Override
			public boolean onTagClick(View view, int position, FlowLayout parent) {

				//ToastUtil.showLong(getApplicationContext(), mcontactNums.get(position));
				
				//移除掉联系人及号码
				mcontactNums.remove(position);
				mcontactNames.remove(position);
				//通知适配器更新
				tagAdapter.notifyDataChanged();

				return true;
			}
		});

	}
	
	/**
	 * 构建短信记录对象
	 * @param msgContent
	 * @return
	 */
	private SendedMsg bulidSendMsg(String msgContent) {
        SendedMsg sendedMsg=new SendedMsg();
        sendedMsg.setContent(msgContent);
        sendedMsg.setFestivalName(mfestival.getName());
        StringBuilder names=new StringBuilder();
        for (String name: mcontactNames) {
            names.append(name+",");
        }
        sendedMsg.setNames(names.substring(0,names.length()-1));
        StringBuilder numbers=new StringBuilder();
        for (String number: mcontactNums) {
            numbers.append(number+",");
        }
        sendedMsg.setNumbers(numbers.substring(0,numbers.length()-1));
        return sendedMsg;
    }
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
	   if(REQUESTCODE == requestCode){
		   if( resultCode == RESULT_OK){
			   Uri contactUri = data.getData();
			   Cursor cursor = this.getContentResolver().query(contactUri, null, null, null, null);
			   
			   cursor.moveToFirst();
			   int columnIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
			   String contactName = cursor.getString(columnIndex);
			   
			   String phoneNum = getContactNumber(cursor);
			   if(!TextUtils.isEmpty(phoneNum)){
				   //接收短信的号码不可以重复
				   if(!mcontactNums.contains(phoneNum)){
					   mcontactNums.add(phoneNum);
					   mcontactNames.add(contactName);
					   
					 //更新适配器
					 tagAdapter.notifyDataChanged();
				   }
			   }
			   cursor.close();
		   }
	   }
	
	}



	@SuppressWarnings("unused")
	private void addTag(String contactName) {

		//TextView textView = (TextView) miInflater.inflate(R.layout.tag, mFlContacts,false);
		//textView.setText(contactName);
	    //这句千万不能少,花了半小时才发现这问题
	   // mFlContacts.addView(textView);
		
	}


	/**
	 * 获取联系人的手机号码
	 * @param cursor
	 * @return
	 */
	private String getContactNumber(Cursor cursor) {
		String phone = null;
		//一个联系人可能有多个联系电话
		//获取手机号码的个数
		int numberCount = cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
		if(numberCount > 0){
			int contactId = cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts._ID));
			Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
			String selection = ContactsContract.CommonDataKinds.Phone.CONTACT_ID+" = "+contactId;
			Cursor phoneCursor = this.getContentResolver().query(uri , null, selection, null, null);
		
			if(phoneCursor.moveToFirst()){
				//手机号码可能有多个,只提取一个
				String number = ContactsContract.CommonDataKinds.Phone.NUMBER;
				int columnIndex = phoneCursor.getColumnIndex(number);
			    phone = phoneCursor.getString(columnIndex);
			}
			phoneCursor.close();
		}
		
		return phone;
	}


	private void initView() {
		meidtmesg = (EditText) findViewById(R.id.wz_edit_content);
		mbtnAdd = (Button) findViewById(R.id.wz_btn_add);
		mFlContacts  = (TagFlowLayout) findViewById(R.id.wz_fl_contacts);
		mfabSend = (FloatingActionButton) findViewById(R.id.wz_fab_send);
		mlayoutLoading = findViewById(R.id.wz_layout_loading);
		
		//隐藏圆形进度条,只在发送短信的时候显示,发送完成隐藏
		mlayoutLoading.setVisibility(View.GONE);
		
		if(msgId != -1){
			msg = FestivalData.getInstance().getMsgByMsgId(msgId);
			meidtmesg.setText(msg.getContent());
		}else{
			MainActivity.instance().speak("请编辑短信后,选择联系人发送");
		}
		
	}


	private void initDatas() {
		Intent intent = this.getIntent();
		mfestivalId = intent.getIntExtra(KEY_FESTIVAL_ID, -1);
		msgId = intent.getIntExtra(KEY_MSG_ID, -1);
		
		mfestival = FestivalData.getInstance().getFestivalById(mfestivalId);
		this.setTitle(mfestival.getName());
		
	}


	public static void toActivity(Context context,int festivalid,int msgid ){
		Intent intent = new Intent(context,SendMesgActivity.class);
		intent.putExtra(KEY_FESTIVAL_ID, festivalid);
		intent.putExtra(KEY_MSG_ID, msgid);
		context.startActivity(intent);
	}
	
	/**
	 * 清空将要发送信息的联系人数据
	 */
	public static void clearContacts(){
		SendMesgActivity.mcontactNames.clear();
		SendMesgActivity.mcontactNums.clear();
		SendMesgActivity.mmesgSendCount=0;
		SendMesgActivity.mtotalCount = 0;
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		//取消注册广播
	   this.unregisterReceiver(msendBroadcastReceiver);
	   this.unregisterReceiver(mdeliverBroadcastReceiver);
	   
	   SendMesgActivity.clearContacts();
	}

}
